<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 百日行动线索收集系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <link href="css/admin-mobile.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .sidebar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            position: fixed;
            top: 0;
            left: 0;
            width: 250px;
            z-index: 1000;
        }
        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            border-radius: 8px;
            margin: 2px 10px;
            transition: all 0.3s ease;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }
        .main-content {
            margin-left: 250px;
            padding: 20px;
        }
        .navbar {
            background: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .content-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 20px;
        }
        .user-card {
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }
        .user-card:hover {
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        .role-badge {
            font-size: 12px;
            padding: 4px 8px;
            border-radius: 20px;
        }
        .role-super_admin { background: #dc3545; color: white; }
        .role-admin { background: #fd7e14; color: white; }
        .role-operator { background: #20c997; color: white; }
        .role-viewer { background: #6c757d; color: white; }
        .status-badge {
            font-size: 12px;
            padding: 4px 8px;
            border-radius: 20px;
        }
        .status-active { background: #d4edda; color: #155724; }
        .status-inactive { background: #f8d7da; color: #721c24; }
        .user-meta {
            font-size: 12px;
            color: #6c757d;
        }
        .btn-action {
            padding: 4px 8px;
            font-size: 12px;
            border-radius: 15px;
        }
    </style>
</head>
<body>
    <!-- 移动端头部 -->
    <div class="mobile-header">
        <button class="mobile-menu-btn" onclick="toggleSidebar()">
            <i class="bi bi-list"></i>
        </button>
        <h5 class="mb-0">用户管理</h5>
        <div class="dropdown">
            <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                <i class="bi bi-person-circle"></i>
            </button>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>个人资料</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item logout-link" href="#"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
            </ul>
        </div>
    </div>
    
    <!-- 侧边栏遮罩层 -->
    <div class="sidebar-overlay"></div>
    
    <!-- 侧边栏 -->
    <nav class="sidebar" id="sidebar">
        <div class="p-3">
            <h5 class="text-white mb-4">
                <i class="bi bi-shield-check me-2"></i>
                管理后台
            </h5>
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="/admin/dashboard.html">
                        <i class="bi bi-speedometer2 me-2"></i>仪表板
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/clues.html">
                        <i class="bi bi-file-text me-2"></i>线索管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/statistics.html">
                        <i class="bi bi-bar-chart me-2"></i>统计分析
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="/admin/users.html">
                        <i class="bi bi-people me-2"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/admin/settings.html">
                        <i class="bi bi-gear me-2"></i>系统设置
                    </a>
                </li>
            </ul>
        </div>
        <div class="mt-auto p-3">
            <button class="btn btn-outline-light btn-sm w-100 logout-link" type="button">
                <i class="bi bi-box-arrow-right me-2"></i>退出登录
            </button>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="main-content">
        <!-- 顶部导航 -->
        <nav class="navbar navbar-expand-lg navbar-light">
            <div class="container-fluid">
                <h4 class="mb-0">用户管理</h4>
                <div class="navbar-nav ms-auto">
                    <div class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle me-2"></i>
                            <span id="adminName">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#"><i class="bi bi-person me-2"></i>个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item logout-link" href="#"><i class="bi bi-box-arrow-right me-2"></i>退出登录</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </nav>

        <!-- 筛选和操作区域 -->
        <div class="content-card">
            <div class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">角色筛选</label>
                    <select class="form-select" id="roleFilter" onchange="loadUsers()">
                        <option value="">全部角色</option>
                        <option value="super_admin">超级管理员</option>
                        <option value="admin">管理员</option>
                        <option value="operator">操作员</option>
                        <option value="viewer">查看员</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">状态筛选</label>
                    <select class="form-select" id="statusFilter" onchange="loadUsers()">
                        <option value="">全部状态</option>
                        <option value="1">启用</option>
                        <option value="0">禁用</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">搜索用户</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="keywordSearch" placeholder="搜索用户名、姓名...">
                        <button class="btn btn-primary" onclick="searchUsers()">
                            <i class="bi bi-search"></i>
                        </button>
                    </div>
                </div>
                <div class="col-md-2">
                    <label class="form-label">&nbsp;</label>
                    <div class="d-grid">
                        <button class="btn btn-success" id="addUserBtn">
                            <i class="bi bi-plus-circle me-2"></i>添加用户
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 用户列表 -->
        <div class="content-card">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">管理员列表</h5>
                <div class="d-flex align-items-center">
                    <span class="text-muted me-3">共 <span id="totalCount">0</span> 个用户</span>
                    <select class="form-select form-select-sm" style="width: auto;" id="pageSizeSelect" onchange="changePageSize()">
                        <option value="10">10条/页</option>
                        <option value="20" selected>20条/页</option>
                        <option value="50">50条/页</option>
                    </select>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户名</th>
                            <th>真实姓名</th>
                            <th>角色</th>
                            <th>状态</th>
                            <th>最后登录</th>
                            <th>创建时间</th>
                            <th>创建人</th>
                            <th width="200">操作</th>
                        </tr>
                    </thead>
                    <tbody id="userTableBody">
                        <!-- 动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <nav aria-label="分页导航">
                <ul class="pagination justify-content-center" id="pagination">
                    <!-- 动态生成 -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <div class="modal fade" id="userModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalTitle">添加用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="userForm">
                        <input type="hidden" id="userId">
                        <div class="mb-3">
                            <label class="form-label">用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="username" required>
                            <div class="form-text">用户名用于登录，3-50个字符</div>
                        </div>
                        <div class="mb-3" id="passwordGroup">
                            <label class="form-label">密码 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="password" required>
                            <div class="form-text">密码至少6个字符</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">真实姓名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="realName" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">角色 <span class="text-danger">*</span></label>
                            <select class="form-select" id="role" required>
                                <option value="">请选择角色</option>
                                <option value="admin">管理员</option>
                                <option value="operator">操作员</option>
                                <option value="viewer">查看员</option>
                            </select>
                            <div class="form-text">
                                <small>
                                    <strong>管理员:</strong> 可管理线索和用户<br>
                                    <strong>操作员:</strong> 可处理线索<br>
                                    <strong>查看员:</strong> 只能查看线索
                                </small>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">邮箱</label>
                            <input type="email" class="form-control" id="email">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">电话</label>
                            <input type="tel" class="form-control" id="phone">
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="isActive" checked>
                                <label class="form-check-label" for="isActive">
                                    启用账户
                                </label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveUserBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 重置密码模态框 -->
    <div class="modal fade" id="resetPasswordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">重置密码</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="resetPasswordForm">
                        <input type="hidden" id="resetUserId">
                        <div class="mb-3">
                            <label class="form-label">用户</label>
                            <input type="text" class="form-control" id="resetUserInfo" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">新密码 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="newPassword" required>
                            <div class="form-text">密码至少6个字符</div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">确认密码 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="confirmPassword" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="resetPasswordBtn">重置密码</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/admin-mobile.js"></script>
    <script>
        // 全局变量
        let currentPage = 1;
        let pageSize = 20;
        let totalPages = 1;
        let currentUser = null;
        let isEditMode = false;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAuth();
            loadUsers();
            
            // 绑定搜索回车事件
            document.getElementById('keywordSearch').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchUsers();
                }
            });
            // 绑定新增用户按钮
            document.getElementById('addUserBtn').addEventListener('click', showAddUserModal);
            // 绑定保存用户按钮
            document.getElementById('saveUserBtn').addEventListener('click', saveUser);
            // 绑定用户表格操作按钮事件委托
            document.getElementById('userTableBody').addEventListener('click', function(event) {
                const editBtn = event.target.closest('.edit-user-btn');
                if (editBtn) {
                    editUser(editBtn.getAttribute('data-user-id'));
                    return;
                }
                const resetBtn = event.target.closest('.reset-password-btn');
                if (resetBtn) {
                    showResetPasswordModal(
                        resetBtn.getAttribute('data-user-id'),
                        resetBtn.getAttribute('data-username'),
                        resetBtn.getAttribute('data-realname')
                    );
                    return;
                }
                const toggleBtn = event.target.closest('.toggle-status-btn');
                if (toggleBtn) {
                    toggleUserStatus(
                        toggleBtn.getAttribute('data-user-id'),
                        toggleBtn.getAttribute('data-new-status') === 'true'
                    );
                    return;
                }
                const deleteBtn = event.target.closest('.delete-user-btn');
                if (deleteBtn) {
                    deleteUser(
                        deleteBtn.getAttribute('data-user-id'),
                        deleteBtn.getAttribute('data-username')
                    );
                    return;
                }
            });
            // 绑定重置密码按钮
            document.getElementById('resetPasswordBtn').addEventListener('click', resetPassword);
            // 绑定所有退出登录按钮
            document.querySelectorAll('.logout-link').forEach(function(el) {
                el.addEventListener('click', function(e) {
                    e.preventDefault();
                    logout();
                });
            });
        });

        // 检查认证状态
        function checkAuth() {
            const token = localStorage.getItem('adminToken');
            if (!token) {
                window.location.href = '/admin/login.html';
                return;
            }
            
            const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
            document.getElementById('adminName').textContent = adminUser.real_name || '管理员';
            currentUser = adminUser;
            
            // 检查权限，只有管理员以上才能看到添加按钮
            if (adminUser.role !== 'admin' && adminUser.role !== 'super_admin') {
                document.getElementById('addUserBtn').style.display = 'none';
            }
        }

        // 加载用户列表
        async function loadUsers() {
            try {
                const token = localStorage.getItem('adminToken');
                const params = new URLSearchParams({
                    page: currentPage,
                    page_size: pageSize,
                    role: document.getElementById('roleFilter').value,
                    is_active: document.getElementById('statusFilter').value,
                    keyword: document.getElementById('keywordSearch').value
                });

                const response = await fetch(`/api/admin/users?${params}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    const data = result.data;
                    
                    renderUserTable(data.list || []);
                    renderPagination(data.pagination || {});
                    document.getElementById('totalCount').textContent = data.pagination?.total || 0;
                } else {
                    console.error('加载用户失败');
                }
            } catch (error) {
                console.error('加载用户错误:', error);
            }
        }

        // 渲染用户表格
        function renderUserTable(users) {
            const tbody = document.getElementById('userTableBody');
            tbody.innerHTML = users.map(user => `
                <tr>
                    <td>${user.id}</td>
                    <td>
                        <strong>${user.username}</strong>
                        ${user.id === currentUser.id ? '<span class="badge bg-info ms-1">当前用户</span>' : ''}
                    </td>
                    <td>${user.real_name}</td>
                    <td>
                        <span class="role-badge role-${user.role}">
                            ${getRoleText(user.role)}
                        </span>
                    </td>
                    <td>
                        <i class="bi bi-circle-fill status-${user.is_active ? 'active' : 'inactive'}"></i>
                        ${user.is_active ? '启用' : '禁用'}
                    </td>
                    <td>
                        ${user.last_login_time ? formatDate(user.last_login_time) : '从未登录'}
                        ${user.last_login_ip ? `<br><small class="text-muted">${user.last_login_ip}</small>` : ''}
                    </td>
                    <td>
                        <small>${formatDate(user.created_at)}</small>
                    </td>
                    <td>${user.creator_name || '-'}</td>
                    <td>
                        <button class="btn btn-outline-primary btn-action edit-user-btn" data-user-id="${user.id}">
                            <i class="bi bi-pencil"></i> 编辑
                        </button>
                        <button class="btn btn-outline-warning btn-action reset-password-btn"
                                data-user-id="${user.id}" data-username="${user.username}" data-realname="${user.real_name}">
                            <i class="bi bi-key"></i> 重置密码
                        </button>
                        <div class="btn-group">
                            <button class="btn btn-outline-secondary btn-action dropdown-toggle" data-bs-toggle="dropdown">
                                更多
                            </button>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item toggle-status-btn" href="#" data-user-id="${user.id}" data-new-status="${!user.is_active}">
                                    <i class="bi bi-${user.is_active ? 'x-circle' : 'check-circle'} me-2"></i>
                                    ${user.is_active ? '禁用' : '启用'}
                                </a></li>
                                ${user.id !== currentUser.id && currentUser.role === 'super_admin' ? `
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item text-danger delete-user-btn" href="#" data-user-id="${user.id}" data-username="${user.username}">
                                    <i class="bi bi-trash me-2"></i>删除
                                </a></li>
                                ` : ''}
                            </ul>
                        </div>
                    </td>
                </tr>
            `).join('');
        }

        // 渲染分页
        function renderPagination(pagination) {
            const paginationEl = document.getElementById('pagination');
            const { current_page = 1, total_pages = 1 } = pagination;
            
            currentPage = current_page;
            totalPages = total_pages;
            
            let html = '';
            
            // 上一页
            html += `
                <li class="page-item ${current_page <= 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${current_page - 1})">上一页</a>
                </li>
            `;
            
            // 页码
            const startPage = Math.max(1, current_page - 2);
            const endPage = Math.min(total_pages, current_page + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                html += `
                    <li class="page-item ${i === current_page ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                    </li>
                `;
            }
            
            // 下一页
            html += `
                <li class="page-item ${current_page >= total_pages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${current_page + 1})">下一页</a>
                </li>
            `;
            
            paginationEl.innerHTML = html;
        }

        // 切换页面
        function changePage(page) {
            if (page >= 1 && page <= totalPages) {
                currentPage = page;
                loadUsers();
            }
        }

        // 改变每页显示数量
        function changePageSize() {
            pageSize = parseInt(document.getElementById('pageSizeSelect').value);
            currentPage = 1;
            loadUsers();
        }

        // 搜索用户
        function searchUsers() {
            currentPage = 1;
            loadUsers();
        }

        // 显示添加用户模态框
        function showAddUserModal() {
            if (!currentUser) {
                alert('请稍候，用户信息未加载完成');
                return;
            }
            isEditMode = false;
            document.getElementById('userModalTitle').textContent = '添加用户';
            document.getElementById('userForm').reset();
            document.getElementById('userId').value = '';
            document.getElementById('passwordGroup').style.display = 'block';
            document.getElementById('password').required = true;
            document.getElementById('isActive').checked = true;
            
            // 根据当前用户权限设置角色选项
            const roleSelect = document.getElementById('role');
            roleSelect.innerHTML = '<option value="">请选择角色</option>';
            
            if (currentUser.role === 'super_admin') {
                roleSelect.innerHTML += '<option value="super_admin">超级管理员</option>';
            }
            if (currentUser.role === 'super_admin' || currentUser.role === 'admin') {
                roleSelect.innerHTML += '<option value="admin">管理员</option>';
                roleSelect.innerHTML += '<option value="operator">操作员</option>';
                roleSelect.innerHTML += '<option value="viewer">查看员</option>';
            }
            
            const modal = new bootstrap.Modal(document.getElementById('userModal'));
            modal.show();
        }

        // 编辑用户
        async function editUser(userId) {
            try {
                const token = localStorage.getItem('adminToken');
                const response = await fetch(`/api/admin/users/${userId}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    const user = result.data;
                    
                    isEditMode = true;
                    document.getElementById('userModalTitle').textContent = '编辑用户';
                    document.getElementById('userId').value = user.id;
                    document.getElementById('username').value = user.username;
                    document.getElementById('realName').value = user.real_name;
                    document.getElementById('role').value = user.role;
                    document.getElementById('email').value = user.email || '';
                    document.getElementById('phone').value = user.phone || '';
                    document.getElementById('isActive').checked = user.is_active;
                    
                    // 编辑模式下隐藏密码字段
                    document.getElementById('passwordGroup').style.display = 'none';
                    document.getElementById('password').required = false;
                    
                    // 设置角色选项
                    const roleSelect = document.getElementById('role');
                    roleSelect.innerHTML = '<option value="">请选择角色</option>';
                    
                    if (currentUser.role === 'super_admin') {
                        roleSelect.innerHTML += '<option value="super_admin">超级管理员</option>';
                    }
                    if (currentUser.role === 'super_admin' || currentUser.role === 'admin') {
                        roleSelect.innerHTML += '<option value="admin">管理员</option>';
                        roleSelect.innerHTML += '<option value="operator">操作员</option>';
                        roleSelect.innerHTML += '<option value="viewer">查看员</option>';
                    }
                    
                    document.getElementById('role').value = user.role;
                    
                    const modal = new bootstrap.Modal(document.getElementById('userModal'));
                    modal.show();
                } else {
                    alert('获取用户信息失败');
                }
            } catch (error) {
                console.error('获取用户信息错误:', error);
                alert('获取用户信息失败');
            }
        }

        // 保存用户
        async function saveUser() {
            console.log('saveUser called');
            try {
                const form = document.getElementById('userForm');
                if (!form.checkValidity()) {
                    console.log('表单校验未通过');
                    form.reportValidity();
                    return;
                }

                const userId = document.getElementById('userId').value;
                const userData = {
                    username: document.getElementById('username').value,
                    real_name: document.getElementById('realName').value,
                    role: document.getElementById('role').value,
                    email: document.getElementById('email').value,
                    phone: document.getElementById('phone').value,
                    is_active: document.getElementById('isActive').checked
                };

                if (!isEditMode) {
                    userData.password = document.getElementById('password').value;
                }

                console.log('userData:', userData);

                const token = localStorage.getItem('adminToken');
                const url = isEditMode ? `/api/admin/users/${userId}` : '/api/admin/users';
                const method = isEditMode ? 'PUT' : 'POST';

                console.log('fetch:', { url, method, userData });
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(userData)
                });

                console.log('fetch response status:', response.status);
                if (response.ok) {
                    alert(isEditMode ? '用户更新成功' : '用户创建成功');
                    bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
                    loadUsers();
                } else {
                    const result = await response.json();
                    console.error('保存用户失败:', result);
                    alert(result.message || '操作失败');
                }
            } catch (error) {
                console.error('保存用户错误:', error);
                alert('操作失败');
            }
        }

        // 启用/禁用用户
        async function toggleUserStatus(userId, newStatus) {
            if (!currentUser) {
                alert('请稍候，用户信息未加载完成');
                return;
            }
            if (userId == currentUser.id) {
                alert('不能禁用自己');
                return;
            }
            const actionText = newStatus ? '启用' : '禁用';
            if (!confirm(`确认要${actionText}该用户吗？`)) {
                return;
            }
            try {
                const token = localStorage.getItem('adminToken');
                const response = await fetch(`/api/admin/users/${userId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({ is_active: newStatus })
                });
                if (response.status === 401) {
                    window.location.href = '/admin/login.html';
                    return;
                }
                const result = await response.json();
                if (response.ok) {
                    alert(`${actionText}成功`);
                    loadUsers();
                } else {
                    alert(result.message || `${actionText}失败`);
                }
            } catch (error) {
                console.error(`${actionText}用户失败:`, error);
                alert(`${actionText}失败：网络错误`);
            }
        }

        // 显示重置密码模态框
        function showResetPasswordModal(userId, username, realName) {
            document.getElementById('resetUserId').value = userId;
            document.getElementById('resetUserInfo').value = `${realName}（${username}）`;
            document.getElementById('resetPasswordForm').reset();
            const modal = new bootstrap.Modal(document.getElementById('resetPasswordModal'));
            modal.show();
        }

        // 重置密码
        async function resetPassword() {
            console.log('resetPassword called');
            try {
                const form = document.getElementById('resetPasswordForm');
                if (!form.checkValidity()) {
                    console.log('表单校验未通过');
                    form.reportValidity();
                    return;
                }

                const userId = document.getElementById('resetUserId').value;
                const newPassword = document.getElementById('newPassword').value;
                const confirmPassword = document.getElementById('confirmPassword').value;

                if (newPassword !== confirmPassword) {
                    console.log('两次输入的密码不一致');
                    alert('两次输入的密码不一致');
                    return;
                }

                const token = localStorage.getItem('adminToken');
                const url = `/api/admin/users/${userId}/reset-password`;
                const method = 'POST';
                console.log('fetch:', { url, method, userId, newPassword });

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({ new_password: newPassword })
                });

                console.log('fetch response status:', response.status);
                if (response.ok) {
                    alert('密码重置成功');
                    bootstrap.Modal.getInstance(document.getElementById('resetPasswordModal')).hide();
                    loadUsers();
                } else {
                    const result = await response.json();
                    console.error('重置密码失败:', result);
                    alert(result.message || '操作失败');
                }
            } catch (error) {
                console.error('重置密码错误:', error);
                alert('重置密码失败');
            }
        }

        // 删除用户（软删除）
        async function deleteUser(userId, username) {
            if (!currentUser) {
                alert('请稍候，用户信息未加载完成');
                return;
            }
            if (userId == currentUser.id) {
                alert('不能删除自己');
                return;
            }
            if (!confirm(`确认要删除用户 ${username} 吗？删除后该用户将无法登录。`)) {
                return;
            }
            try {
                const token = localStorage.getItem('adminToken');
                const response = await fetch(`/api/admin/users/${userId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({ is_active: 0 })
                });
                if (response.status === 401) {
                    window.location.href = '/admin/login.html';
                    return;
                }
                const result = await response.json();
                if (response.ok) {
                    alert('用户已删除');
                    loadUsers();
                } else {
                    alert(result.message || '删除失败');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                alert('删除失败：网络错误');
            }
        }

        // 工具函数
        function getRoleText(role) {
            const roleMap = {
                'super_admin': '超级管理员',
                'admin': '管理员',
                'operator': '操作员',
                'viewer': '查看员'
            };
            return roleMap[role] || role;
        }

        function formatDate(dateString) {
            console.log('formatDate called with:', dateString);
            if (!dateString) return '-';
            const date = new Date(dateString);
            console.log('formatted date:', date.toLocaleString('zh-CN'));
            return date.toLocaleString('zh-CN');
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminUser');
            window.location.href = '/admin/login.html';
        }
    </script>
</body>
</html>